package com.lottery.api.controller.member;


import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.lottery.api.annotation.CheckLoginAop;
import com.lottery.api.annotation.CoerceLoginAop;
import com.lottery.api.service.*;
import com.lottery.common.contants.*;
import com.lottery.common.entity.*;
import com.lottery.common.service.*;
import com.lottery.common.thread.SendMsgTool;
import com.lottery.common.utils.*;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.hutool.core.util.RandomUtil;
import springfox.documentation.annotations.ApiIgnore;

import static com.lottery.common.contants.Constants.*;
import static com.lottery.common.contants.SmsConstants.SMS_FORGOT_CODE;
import static com.lottery.common.contants.SmsConstants.SMS_REGISTER_CODE;

/**
 * @author furutaka
 */
@RestController
@RequestMapping("/member")
@CrossOrigin(origins = "http://192.168.101.4", maxAge = 3600)
@Slf4j
@Api(value = "/member",tags="会员操作类")
public class MemberController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private ReQueryResult result = new ReQueryResult();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");


    @Autowired
    private MemberInfoService mis;
    @Autowired
    private SmsMssageService smsMssageService;
    @Autowired
    private FileUploadService fileUploadService;
    @Resource
    private DecryptToObjectService decryptToObjectService;
    @Autowired
    private MemberCertifyService memberCertifyService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private FocusMemberRecordService focusMemberRecordService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private MemberInfoSubService miss;
    @Autowired
    private ShortReportInfoService shortReportInfoService;
    @Autowired
    private ForecastInfoService forecastInfoService;

    @Value("${base.upload.path}")
    private String uploadPath;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @ApiOperation(value = "app用户登录接口")
    @ApiImplicitParam(name = "json",value = "{\"phone\":\"123\",\"password\":\"123\",\"loginType\":\"int类型 1安卓 2ios 3 游客登录\"}",dataType="String")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ReQueryResult login(String json) throws Exception {
        result = new ReQueryResult();
        logger.info("login in");
        MemberInfo info=decryptToObjectService.jsonToObject(json,MemberInfo.class);
        result=mis.loginMember(info);
        return  result;
    }



    /**
     * app用户注册接口
     * @param  request MemberInfo对象 入参 {"phone":"","password":"","smsCode":""}
     * @return
     */
    @ApiOperation(value = "app用户注册接口")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiImplicitParam(name = "json",value = "{\"phone\":\"\",\"password\":\"\",\"smsCode\":\"\"}",dataType="String")
    public ReQueryResult register(HttpServletRequest request,String json) throws Exception {
        logger.info("register in");
        result=new ReQueryResult();
        MemberInfo member= decryptToObjectService.jsonToObject(json,MemberInfo.class);
        logger.info("member is {}",JSON.toJSONString(member));

        NutMap map = RedisUtils.getConfigFromRedis("0102",NutMap.class);
        result=checkSmsCode(member.getPhone(),member.getSmsCode(),map.getString("value"));
        if (!result.getResultCode().equals(TYPE_ZERO_ZERO_STR)){
            return  result;
        }
        result=MethodConstants.checkPwd(member.getPassword());
        if (!result.getResultCode().equals(TYPE_ZERO_ZERO_STR)){
            return  result;
        }
        member.setNickName("用户-"+member.getPhone());
        member.setPassword(AES.Encrypt(member.getPassword()));
        member.setId(null);
        Integer count=mis.saveAndCheck(member);
        if (count==null||count==0){
            result.error(REGIST_PHONE_FAILURE);
            return  result;
        }
        redisTemplate.delete("registerCode"+member.getPhone());
        result.success(SUCCESS_DESC);
        return result;
    }


    /**
     * ios游客注册接口
     * @param  request MemberInfo对象 入参 {"phone":"","password":"","smsCode":""}
     * @return
     */
    @ApiOperation(value = "ios游客注册接口")
    @RequestMapping(value = "/iosRegister", method = RequestMethod.POST)
    @ApiImplicitParam(name = "json",value = "{\"phone\":\"\",\"password\":\"\",\"smsCode\":\"\"}",dataType="String")
    public ReQueryResult iosRegister(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo,String json) throws Exception {
        logger.info("register in");
        result=new ReQueryResult();
        MemberInfo member= decryptToObjectService.jsonToObject(json,MemberInfo.class);
        logger.info("member is {}",JSON.toJSONString(member));

        result=checkSmsCode(member.getPhone(),member.getSmsCode(),SMS_REGISTER_CODE);
        if (!result.getResultCode().equals(TYPE_ZERO_ZERO_STR)){
            return  result;
        }

        result=MethodConstants.checkPwd(member.getPassword());
        if (!result.getResultCode().equals(TYPE_ZERO_ZERO_STR)){
            return  result;
        }
        member.setPassword(AES.Encrypt(member.getPassword()));
        member.setNickName("用户-"+member.getPhone());
        member.setId(memberInfo.getId());
        boolean flag =mis.updateById(member);
        if (!flag){
            result.error(REGIST_FAILURE);
            return  result;
        }
        redisTemplate.delete(SMS_REGISTER_CODE+member.getPhone());
        result.success(SUCCESS_DESC);
        return result;
    }


    public ReQueryResult checkSmsCode(String phone,String smsCode,String smsType){
        Object o=redisTemplate.opsForValue().get(smsType+phone);
        if (o==null||StringUtils.isEmpty(o.toString())){
            result.error(CODE_LOSE);
            return  result;
        }
        if (!o.toString().equals(smsCode)){
            result.error(CODE_ERROR);
            return  result;
        }
        result.success(SUCCESS_DESC);
        return result;
    }


    /**
     * 忘记密码
     * @param request
     * @return
     */
    @ApiOperation(value = "忘记密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "手机号",dataType="String"),
            @ApiImplicitParam(name = "smsCode",value = "验证码",dataType="String")
    })
    @RequestMapping(value = "/forgot", method = RequestMethod.POST)
    public ReQueryResult forgot(HttpServletRequest request,String phone,String smsCode) throws Exception {
        result=new ReQueryResult();
        NutMap map = RedisUtils.getConfigFromRedis("0104",NutMap.class);
        result=checkSmsCode(phone,smsCode,map.getString("value"));
        if (!result.getResultCode().equals(TYPE_ZERO_ZERO_STR)){
            return  result;
        }
//        redisTemplate.delete("forgotCode"+member.getPhone());
        result.success(SUCCESS_DESC);
        return  result;
    }

    /**
     * 忘记密码
     * @param request
     * @return
     */
    @ApiOperation(value = "重置密码")
    @ApiImplicitParam(name = "json",value = "{\"phone\":\"\",\"password\":\"\",\"smsCode\":\"\"}",dataType="String")
    @RequestMapping(value = "/reset", method = RequestMethod.POST)
    public ReQueryResult reset(HttpServletRequest request,String json) throws Exception {
        result=new ReQueryResult();
        MemberInfo member=decryptToObjectService.jsonToObject(json,MemberInfo.class);
        NutMap map = RedisUtils.getConfigFromRedis("0104",NutMap.class);
        result=checkSmsCode(member.getPhone(),member.getSmsCode(),map.getString("value"));
        if (!result.getResultCode().equals(TYPE_ZERO_ZERO_STR)){
            return  result;
        }

        UpdateWrapper<MemberInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("phone",member.getPhone());
        updateWrapper.set("password",AES.Encrypt(member.getPassword()));
        redisTemplate.delete(SMS_FORGOT_CODE+member.getPhone());
        boolean flag =mis.update(updateWrapper);
        if (!flag){
            result.error(UPDATE_FAILED_DESC);
            return  result;
        }
        result.success(SUCCESS_DESC);
        return  result;
    }

    /**
     * 发送短信验证码
     * @param type 发送验证码类型 1登录 2.注册
     * @param phone 手机号
     * @return
     */
    @ApiOperation(value = "发送短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type",value = "01 登录 02 注册",dataType="String"),
            @ApiImplicitParam(name = "phone",value = "手机号",dataType="String")
    })
    @RequestMapping(value = "/smsCode", method = RequestMethod.POST)
    @CheckLoginAop
    public ReQueryResult smsCode(HttpServletRequest request, @ApiIgnore() MemberInfo memberInfo,
                                 @RequestParam(name="type", required = false) String type,
                                 @RequestParam(name="phone", required = false) String phone){
        logger.info("smsCode");
        result=new ReQueryResult();
        NutMap nutMap=new NutMap();
        nutMap.setv("phone",phone);
        nutMap.setv("smsType",type);
        log.info("nut map is {} ",JSON.toJSONString(nutMap));

        if (StringUtils.isEmpty(nutMap.getString("phone"))){
            log.info("phone is null");
            result.error(PARAMS_WRONG_DESC);
            return  result;
        }
        if (!"01".equals(nutMap.getString("smsType"))){
            QueryWrapper<MemberInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",nutMap.getString("phone"));
            MemberInfo m=mis.getOne(queryWrapper);
            if (m!=null&&"02".equals(nutMap.getString("smsType"))){
                result.error(REGIST_PHONE_FAILURE);
                return  result;
            }
            if (m==null&&"04".equals(nutMap.getString("smsType"))){
                result.error("该手机号尚未注册");
                return  result;
            }
        }

        String smsType="";
        NutMap map = RedisUtils.getConfigFromRedis("01"+nutMap.getString("smsType"),NutMap.class);
        NutMap smsMap = RedisUtils.getConfigFromRedis("07"+nutMap.getString("smsType"),NutMap.class);

        smsType=map.getString("value");
        nutMap.setv("smsTypeStr",smsType);
        nutMap.setv("templateCode",smsMap.getString("value"));
        boolean flag= RedisUtils.checkRedisLock(smsType+"Click"+nutMap.getString("phone"),59 );
        if (!flag){
            result.error(CODE_GET_OFTEN_ERROR);
            return  result;
        }

        String code=String.valueOf(new Random().nextInt(8999) + 1000);
        nutMap.setv("code", code);
        nutMap.setv("sendType", TYPE_ONE);//发送类型 1 验证码 2 消息通知
        log.info("sms code is {}",code);
        redisTemplate.opsForValue().set(nutMap.getString("smsTypeStr")+nutMap.getString("phone"),nutMap.getString("code"),5*60, TimeUnit.SECONDS);
        try {
            SendMsgTool.getInstance().addSend(nutMap);
//            result=sms.sendMsg(nutMap);
        } catch (Exception e) {
            redisTemplate.delete(smsType+"Click"+nutMap.getString("phone"));
            e.printStackTrace();
        }
        result.success(CODE_SUCCESS);
        result.setData(code);
        return  result;
    }


    /**
     * 用户登出
     * @return request header{ token ,phone}
     */
    @CoerceLoginAop
    @ApiOperation(value = "用户登出")
    @RequestMapping(value = "", method = RequestMethod.PATCH)
    public ReQueryResult<MemberInfo> logOut(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo){
        result=new ReQueryResult();
        redisTemplate.opsForHash().delete("loginApp",memberInfo.getPhone());
        redisTemplate.opsForHash().delete("loginMember",memberInfo.getBaseToken());
        redisTemplate.opsForHash().delete("loginMap",memberInfo.getId().toString());
        result.success(SUCCESS_DESC);
        return  result;
    }

    /**
     * 获取用户信息
     * @param request header{ token ,phone}
     * @return
     */
    @CoerceLoginAop
    @ApiOperation(value = "获取用户信息")
    @RequestMapping(value = "", method = RequestMethod.GET)
        public ReQueryResult<MemberInfo> getInformation(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo){
            result=new ReQueryResult();
        MemberInfo info = mis.getById(memberInfo.getId());
        boolean flag=checkPromote(info.getMemberIdentify(),memberInfo.getId());
        if (flag){
            info.setIsPromote(TYPE_ZERO);
        }
        info.setPassword("");
        Date date=new Date();
        if (info.getExpiredTime()!=null&&info.getExpiredTime().after(date)){
            info.setIsExpired(TYPE_ZERO);
        }
        result.setData(info);
        result.setResultObj(MemberInfo.class);
        result.success(SUCCESS_DESC);
        return  result;
    }



    @CoerceLoginAop
    @ApiOperation(value = "发起实名认证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type",value = " 1 入驻大神 2入驻专家 3实名认证 ",dataType="Integer"),
            @ApiImplicitParam(name = "id",value = "更新时必填",dataType="Long"),
            @ApiImplicitParam(name = "name",value = "姓名",dataType="String"),
            @ApiImplicitParam(name = "card",value = "身份证号",dataType="String"),
            @ApiImplicitParam(name = "cardFrontImage",value = "身份证正面",dataType="String"),
            @ApiImplicitParam(name = "cardBackImage",value = "身份证背面",dataType="String")
    })
    @RequestMapping(value = "/certify", method = RequestMethod.POST)
    public ReQueryResult certify(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo,
                                 String id,String name,String card,Integer type,String cardFrontImage,String cardBackImage){
        result=new ReQueryResult();
        boolean flag=checkPromote(type,memberInfo.getId());
        if (!flag){
            result.error("尚未满足申请条件");
            return  result;
        }

        MemberCertify memberCertify=new MemberCertify();
        if (id!=null){
            MemberCertify certify=memberCertifyService.getById(id);
            if (certify!=null&&certify.getStatus()!=TYPE_THREE){
                result.error(USER_CERTIFY_AWAIT);
                return  result;
            }
        }
        if (StringUtils.isNotBlank(id)){
            memberCertify.setId(Long.valueOf(id));
        }
        memberCertify.setMemberId(memberInfo.getId()).setName(name).setCard(card).setStatus(TYPE_TWO).setPhone(memberInfo.getPhone())
                .setType(type).setCardFrontImage(cardFrontImage).setCardBackImage(cardBackImage);
        memberCertifyService.saveOrUpdate(memberCertify);
        MemberInfo info=new MemberInfo();
        info.setIsCertify(TYPE_TWO);
        info.setId(memberInfo.getId());
        mis.updateById(info);
        result.success("提交成功，请等待审核");
        return  result;
    }

    /**
     * 获取会员认证信息
     * @param request header{ token ,phone}
     * @return
     */
    @CoerceLoginAop
    @ApiOperation(value = "获取会员认证信息")
    @RequestMapping(value = "/certify", method = RequestMethod.GET)
    public ReQueryResult<MemberCertify> getCertify(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo){
        result=new ReQueryResult();
        QueryWrapper<MemberCertify>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("member_id",memberInfo.getId()).eq("type",TYPE_ONE).orderByDesc("id");
        queryWrapper.last(" limit 1");
        MemberCertify certify=memberCertifyService.getOne(queryWrapper);
        result.setData(certify);
        result.success(SUCCESS_DESC);
        return  result;
    }

    /**
     * 上传头像
     * @param request header{ token ,phone}
     * @param file  input type=file
     * @return
     */
    @CoerceLoginAop
    @ApiOperation(value = "更新用户详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file",value = "用户头像",dataType="file"),
            @ApiImplicitParam(name = "nickName",value = "昵称",dataType="String"),
            @ApiImplicitParam(name = "intro",value = "简介",dataType="String")
    })
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public ReQueryResult uploadInformation(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo,@RequestParam(name="file", required = false) MultipartFile file,
                                           String avatar,String nickName,String intro){
        log.info(" in   uploadInformation");
        result=new ReQueryResult();
        MemberInfo info=new MemberInfo();
        info.setId(memberInfo.getId());
        info.setAvatar(avatar);
        info.setNickName(nickName);
        info.setIntro(intro);
        if (file!=null&&StringUtils.isNotEmpty(file.getOriginalFilename())){
            logger.info("Filename is {}",file.getOriginalFilename());
            String fileName = file.getOriginalFilename();
            fileName=System.currentTimeMillis()+RandomUtil.randomNumbers(6)+fileName.substring(fileName.lastIndexOf("."));
            try {
                fileUploadService.uploadFile(fileName,file.getInputStream(),"1");
                info.setAvatar(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(ExceptionUtils.getFullStackTrace(e));
//                result.error(UPDATE_FAILED_DESC);
//                return result;
            }
        }
        log.info("member info is {}",JSON.toJSONString(info));
        boolean count=mis.updateById(info);
        if(!count){
            result.error(UPDATE_FAILED_DESC);
            return  result;
        }
        logger.info("update success");
        result.success(SUCCESS_DESC);
        return  result;
    }

    @CoerceLoginAop
    @ApiOperation(value = "更新用户详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "avatar",value = "用户头像",dataType="String"),
            @ApiImplicitParam(name = "nickName",value = "昵称",dataType="String"),
            @ApiImplicitParam(name = "intro",value = "简介",dataType="String")
    })
    @RequestMapping(value = "/uploadInformation", method = RequestMethod.POST)
    public ReQueryResult uploadInformation2(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo,
                                           String avatar,String nickName,String intro){
        log.info(" in   uploadInformation");
        result=new ReQueryResult();
        MemberInfo info=new MemberInfo();
        info.setId(memberInfo.getId());
        info.setAvatar(avatar);
        info.setNickName(nickName);
        info.setIntro(intro);
        log.info("member info is {}",JSON.toJSONString(info));
        boolean count=mis.updateById(info);
        if(!count){
            result.error(UPDATE_FAILED_DESC);
            return  result;
        }
        logger.info("update success");
        result.success(SUCCESS_DESC);
        return  result;
    }

//
//    @ApiOperation(value = "获得会员购买价格")
//    @RequestMapping(value = "/variable", method = RequestMethod.GET)
//    public ReQueryResult variable(){
//        result=new ReQueryResult();
//        List<SysConfig>list=RedisUtils.getConfigFromRedisByType("03",SysConfig.class);
//        result.setData(list);
//        result.success(SUCCESS_DESC);
//        return  result;
//    }


    @CheckLoginAop
    @ApiOperation(value = "获得会员购买价格")
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @RequestMapping(value = "/memberPrice", method = RequestMethod.GET)
    public ReQueryResult<List<SysConfig>> memberPrice(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo){
        result=new ReQueryResult();
        List<SysConfig>list=RedisUtils.getConfigFromRedisByType("03",SysConfig.class);
        QueryWrapper<OrderInfo>queryWrapper=new QueryWrapper<>();
        queryWrapper.select("type_value");
        queryWrapper.eq("member_id",memberInfo.getId()).eq("order_type",TYPE_THREE).eq("status",TYPE_ZERO);
        List<OrderInfo> olist=orderInfoService.list(queryWrapper);
        //已购买过的 提示续费
        for(SysConfig sysConfig:list){
            sysConfig.setIsPay(TYPE_ONE);
            NutMap nutMap= JSON.parseObject(sysConfig.getValue(),NutMap.class);
            sysConfig.setValue(nutMap.getString("value"));
            sysConfig.setDiscount(nutMap.getString("discount"));
//            sysConfig.setDiscount("");
//            if (sysConfig.getCode().equals("0303")||sysConfig.getCode().equals("0304"))
//                sysConfig.setDiscount("9.5");
            for(OrderInfo orderInfo:olist){
                if (orderInfo.getTypeValue().equals(sysConfig.getCode())){
                    sysConfig.setIsPay(TYPE_ZERO);
                    break;
                }
            }
        }
        result.setData(list);
        result.success(SUCCESS_DESC);
        return  result;
    }

    @CoerceLoginAop
    @ApiOperation(value = "用户关注列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "focusType",value = "类型 1 用户 2文章",dataType="String"),
            @ApiImplicitParam(name = "index",value = "页码 ",dataType="Integer"),
            @ApiImplicitParam(name = "length",value = "长度",dataType="Integer")
    })
    @RequestMapping(value = "/focus", method = RequestMethod.GET)
    public ReQueryResult focusAll(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo,
                                  Integer index,Integer length, Integer focusType){
        log.info(" in   uploadInformation");
        result=new ReQueryResult();

        QueryWrapper<MemberInfo> queryWrapper = new QueryWrapper<>();
        if(focusType==TYPE_ONE){
            queryWrapper.in("id",
                    " select focus_value from re_focus_member_record where focus_type=1 and member_id= "+memberInfo.getId());
        }
        if(focusType==TYPE_TWO){
            queryWrapper.in("id",
                    " select focus_value from re_focus_member_record where focus_type=1 and member_id= "+memberInfo.getId());
        }
        queryWrapper.eq("is_hot",TYPE_ZERO).eq("type",TYPE_ONE)
        .eq("is_del",TYPE_ONE).orderByDesc("id");

        Page<MemberInfo> page = new Page<>(index,length);
        IPage<MemberInfo> list=mis.page(page,queryWrapper);
        result.setData(list);


        result.success(SUCCESS_DESC);
        return  result;
    }


    @CoerceLoginAop
    @ApiOperation(value = "用户关注")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "focusId",value = "用户id",dataType="String"),
    })
    @RequestMapping(value = "/focus", method = RequestMethod.POST)
    public ReQueryResult focus(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo,
                                            Long focusId){
        log.info(" in   uploadInformation");
        result=new ReQueryResult();
        FocusMemberRecord info=new FocusMemberRecord();
        info.setMemberId(memberInfo.getId());
        info.setFocusValue(focusId);
        log.info("member info is {}",JSON.toJSONString(info));
        boolean count=focusMemberRecordService.save(info);
        if(!count){
            result.error(UPDATE_FAILED_DESC);
            return  result;
        }
        logger.info("update success");
        result.setData(info.getId());
        result.success(SUCCESS_DESC);
        return  result;
    }
    @CoerceLoginAop
    @ApiOperation(value = "删除用户关注")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "focusId",value = "用户id",dataType="String"),
    })
    @RequestMapping(value = "/focus", method = RequestMethod.DELETE)
    public ReQueryResult delFocus(HttpServletRequest request,@ApiIgnore()MemberInfo memberInfo,
                               Long id){
        log.info(" in   uploadInformation");
        result=new ReQueryResult();
        QueryWrapper<FocusMemberRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("focus_type",TYPE_ONE).eq("focus_value",id).eq("member_id",memberInfo.getId());
        boolean count=focusMemberRecordService.remove(queryWrapper);
        if(!count){
            result.error(UPDATE_FAILED_DESC);
            return  result;
        }
        logger.info("update success");
        result.success(SUCCESS_DESC);
        return  result;
    }

    /**
     * 文件下载
     * @param request
     * @param fileName 文件名
     * @param type
     * @param model
     * @return
     */
    @RequestMapping(value="/download/{fileName}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                           @PathVariable String fileName,String type,
                                           Model model){
        logger.info(" user dowload in ");
//        return fus.download(fileName,type);

        logger.info(" user dowload in ");
        //下载文件路径
        String path = uploadPath;
        File file = new File(path + File.separator + fileName);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = null;
        ResponseEntity<byte[]> byteFIle=null;
        logger.info(" file is {} ",file);
        try {
            downloadFielName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
            //通知浏览器以attachment（下载方式）打开图片
            headers.setContentDispositionFormData("attachment", downloadFielName);
            //application/octet-stream ： 二进制流数据（最常见的文件下载）。
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            byteFIle=new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                    headers, HttpStatus.CREATED);
        } catch (Exception e) {
            logger.error(String.valueOf(e));
            e.printStackTrace();
            return byteFIle;
        } finally {
            return byteFIle;
        }
    }

    /**
     * 初始化
     * @return
     */
    @RequestMapping(value = "/init", method = RequestMethod.POST)
    public ReQueryResult init(){
        result=new ReQueryResult();
        List<SysConfig> slist=sysConfigService.list();
        for (SysConfig sysConfig : slist) {
            redisTemplate.opsForHash().put(DATA_CACHE_SYS_CONFIG, sysConfig.getCode(), JSON.toJSONString(sysConfig));
        }
        List<String>list=new ArrayList<String>();
        for(int i=0;i<slist.size();i++){
            list.add(slist.get(i).getCode());
        }
        clean(list,DATA_CACHE_SYS_CONFIG);
        logger.info("cache sysConfig data success... dataNum={}", slist.size());

        result.success(SUCCESS_DESC);
        return  result;
    }

    @ApiOperation(value = "阿里oss临时凭证")
    @RequestMapping(value = "/sts", method = RequestMethod.GET)
    public ReQueryResult STSAssumeRoleAccess(){
        log.info("阿里oss临时凭证");
        result=new ReQueryResult();
        result=fileUploadService.getSTSToken();
        log.info("result is {}",JSON.toJSONString(result));
        return  result;
    }


    public void clean(List<?>list,String hkey){
        if (redisTemplate == null) {
            return;
        }
        Set<Object> set=redisTemplate.opsForHash().keys(hkey);
        Iterator<Object> it = set.iterator();
        while (it.hasNext()) {
            Object str = it.next();
            if (!list.contains(str)){
                redisTemplate.opsForHash().delete(hkey,str);
            }
        }
    }


    /**
     * 鉴定是否达到晋升条件
     * @return
     */
    public boolean checkPromote(Integer type,Long memberId){
        if (type==3)
            return true;
        Integer count=0;
        boolean flag=false;
        QueryWrapper<ShortReportInfo> sQueryWrapper=new QueryWrapper<>();
        sQueryWrapper.eq("member_id",memberId);
        count+=shortReportInfoService.count(sQueryWrapper);
        QueryWrapper<ForecastInfo> fQueryWrapper=new QueryWrapper<>();
        sQueryWrapper.eq("member_id",memberId);
        count+=forecastInfoService.count(fQueryWrapper);

        if (type==TYPE_TWO){
            flag=true;
            if (count<0){
                flag=false;
            }
        }
        if (type==TYPE_ONE){
            QueryWrapper<MemberInfoSub> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("member_id",memberId);
            MemberInfoSub sub=miss.getOne(queryWrapper);
            if (sub!=null){
                if (sub.getRedEven()>0||(sub.getEarningsRate()>0&&sub.getWinRate()>0&&count>0)){
                    flag=true;
                }
            }


        }

        return  flag;
    }


}
